package com.ruoyi.erp.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.erp.mapper.PayrollMapper;
import com.ruoyi.erp.domain.Payroll;
import com.ruoyi.erp.service.IPayrollService;
import com.ruoyi.common.core.text.Convert;

/**
 * 员工每月成本Service业务层处理
 * 
 * @author sauger
 * @date 2022-03-10
 */
@Service
public class PayrollServiceImpl implements IPayrollService 
{
    @Autowired
    private PayrollMapper payrollMapper;

    /**
     * 查询员工每月成本
     * 
     * @param id 员工每月成本主键
     * @return 员工每月成本
     */
    @Override
    public Payroll selectPayrollById(Integer id)
    {
        return payrollMapper.selectPayrollById(id);
    }

    /**
     * 查询员工每月成本列表
     * 
     * @param payroll 员工每月成本
     * @return 员工每月成本
     */
    @Override
    public List<Payroll> selectPayrollList(Payroll payroll)
    {
        return payrollMapper.selectPayrollList(payroll);
    }

    /**
     * 新增员工每月成本
     * 
     * @param payroll 员工每月成本
     * @return 结果
     */
    @Override
    public int insertPayroll(Payroll payroll)
    {
        payroll.setCreateTime(DateUtils.getNowDate());
        //处理该成本已存在的情况
        Payroll search = new Payroll();
        search.setUserId(payroll.getUserId());
        search.setYear(payroll.getYear());
        search.setMonth(payroll.getMonth());
        List<Payroll> exist = selectPayrollList(search);
        if (!exist.isEmpty())
        {
            payroll.setId(exist.get(0).getId());
            calculateTotalFee(payroll);
            return payrollMapper.updatePayroll(payroll);
        }else{
            //计算total_fee 缓存到数据中
            calculateTotalFee(payroll);
            return payrollMapper.insertPayroll(payroll);
        }

    }

    /**
     * 修改员工每月成本
     * 
     * @param payroll 员工每月成本
     * @return 结果
     */
    @Override
    public int updatePayroll(Payroll payroll)
    {
        payroll.setUpdateTime(DateUtils.getNowDate());
        calculateTotalFee(payroll);
        return payrollMapper.updatePayroll(payroll);
    }

    /**
     * 批量删除员工每月成本
     * 
     * @param ids 需要删除的员工每月成本主键
     * @return 结果
     */
    @Override
    public int deletePayrollByIds(String ids)
    {
        return payrollMapper.deletePayrollByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除员工每月成本信息
     * 
     * @param id 员工每月成本主键
     * @return 结果
     */
    @Override
    public int deletePayrollById(Integer id)
    {
        return payrollMapper.deletePayrollById(id);
    }

    private void calculateTotalFee(Payroll payroll)
    {
        BigDecimal total = new BigDecimal("0");
        if (payroll.getSalary() != null) total = total.add(payroll.getSalary()); //工资
        if (payroll.getAccumulationFund() != null) {total = total.add(payroll.getAccumulationFund()); }//公积金
        if (payroll.getInsurance() != null) total = total.add(payroll.getInsurance());//社保
        if (payroll.getProxyFee() != null) total = total.add(payroll.getProxyFee());//费用-代理
        payroll.setBillFee(total.multiply(BigDecimal.valueOf(0.06)));
        if (payroll.getBonusFee() != null) total = total.add(payroll.getBonusFee());
        if (payroll.getBillFee() != null) total = total.add(payroll.getBillFee());
        if (payroll.getComputerFee() != null) total = total.add(payroll.getComputerFee());
        if (payroll.getExpenseFee() != null) total = total.add(payroll.getExpenseFee());

        if (payroll.getOtherFee() != null) total = total.add(payroll.getOtherFee());

        payroll.setTotalFee(total);
    }

    @Override
    public String importData(List<Payroll> payrolls, String operator) {
        if (StringUtils.isNull(payrolls) || payrolls.size() == 0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Payroll payroll: payrolls)
        {
            try
            {
                this.insertPayroll(payroll);
                successNum++;
            }catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、UID:" + payroll.getUserId() + " 姓名：" +payroll.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }
}
